﻿using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.U2D;
using Object = UnityEngine.Object;

namespace Framework
{
    public class ResLoader : ILoader
    {
        private List<ILoader> _subLoaders;

        private Dictionary<string, Object> _assetDict;

        private static Dictionary<string, object> _spriteAtlasDict = new Dictionary<string, object>();

        public ResLoader()
        {
            _assetDict = new Dictionary<string, Object>();
            _subLoaders = new List<ILoader>();
        }

        public GameObject LoadGameObject(string path, bool instantiate = false)
        {
            if (!_assetDict.TryGetValue(path, out Object asset))
            {
                asset = AssetManager.Instance.GetAsset<GameObject>(path);

                if (asset == null)
                {
                    asset = Resources.Load<GameObject>(path);
                }
                
                if(asset == null)
                {
                    Debug.LogError("加载失败 path：" + path);
                    return null;
                }
                _assetDict.Add(path, asset);
            }
            
            if (instantiate)
                return Object.Instantiate(asset) as GameObject;

            return asset as GameObject;
        }
        
        public void LoadGameObjectAsync(string path, Action<GameObject> onComplete, bool instantiate)
        {
            var loader = Resources.LoadAsync<GameObject>(path);
            loader.completed += operation =>
            {
                if (_assetDict.TryGetValue(path, out var asset))
                {
                    asset = _assetDict[path];
                }
                else
                {
                    asset = loader.asset as GameObject;
                    _assetDict.Add(path, asset);
                }
                
                onComplete(asset as GameObject);
                if(instantiate)
                    Object.Instantiate(asset);
            };
        }

        public Sprite LoadSprite(string path)
        {
            if (_assetDict.TryGetValue(path, out Object asset))
            {
                asset = _assetDict[path];
            }
            else
            {
                asset = Resources.Load<Sprite>(path);
                if(asset == null)
                {
                    Debug.LogError("加载失败 path：" + path);
                    return null;
                }
                _assetDict.Add(path, asset);
            }

            return asset as Sprite;
        }

        public Texture LoadTexture(string path)
        {
            if (_assetDict.TryGetValue(path, out Object asset))
            {
                asset = _assetDict[path];
            }
            else
            {
                asset = Resources.Load<Texture>(path);
                if (asset == null)
                {
                    Debug.LogError("加载失败 path: "+ path);
                    return null;
                }
                _assetDict.Add(path, asset);
            }
            return asset as Texture;
        }
        
        /////////////////////////////////////SpriteAtlas////////////////////////////////////

        public void LoadSpriteAtlas(string path, Action<SpriteAtlas> onComplete)
        {
            Debug.Log("Load UISpriteAtlas:" + path);
            ResourceRequest loader = Resources.LoadAsync<SpriteAtlas>(path);
            loader.completed += operation =>
            {
                if (!_spriteAtlasDict.TryGetValue(path, out var asset))
                {
                    asset = loader.asset;
                    _spriteAtlasDict.Add(path, asset);
                }

                onComplete(asset as SpriteAtlas);
            };
        }

        public Sprite GetAtlasSprite(string assetName)
        {
            string[] moduleNameParts = assetName.Split('_');
            string spriteAtlasName = "SpriteAtlas/"+moduleNameParts[0] + "_" + moduleNameParts[1];

            if (_spriteAtlasDict.TryGetValue(spriteAtlasName, out var atlas))
            {
                Sprite sprite = (atlas as SpriteAtlas)?.GetSprite(assetName);
                if(sprite == null)
                    Debug.LogError("Sprite未找到： name:" + assetName);
                return sprite;
            }
                
            Debug.LogError("图集未加载： path:" + spriteAtlasName);
            return null;
        }
        

        public void UnloadAsset(string path, bool unloadDependencies = false)
        {
            
        }

        public void UnloadAllAsset()
        {
            if(_subLoaders != null)
                foreach (var loader in _subLoaders)
                    loader.UnloadAllAsset();
            
            // foreach (var asset in _assetDict) Resources.UnloadAsset(asset.Value);
        }
 
        public void AddSubLoader(ILoader resLoader)
        {
            if (_subLoaders == null)
                _subLoaders = new List<ILoader>();

            _subLoaders.Add(resLoader);
        }
        
        //====================加载文本和二进制=====================================
        public string LoadText(string path)
        {
            return File.ReadAllText(path);
        }
        
    }
}